package com.zhuxi.controller;

import com.zhuxi.dao.LagouAuthCodeRepository;
import com.zhuxi.pojo.LagouAuthCode;
import com.zhuxi.service.EmailService;
import com.zhuxi.util.CodeUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/code")
public class CodeController {

    @Reference
    private EmailService emailService;

    @Autowired
    private LagouAuthCodeRepository lagouAuthCodeRepository;

    @GetMapping("/create/{email}")
    public Boolean create(@PathVariable String email) {
        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setEmail(email);
        String code = CodeUtils.createCode();
        lagouAuthCode.setCode(code);
        Date now = new Date();
        lagouAuthCode.setCreateTime(now);
        lagouAuthCode.setExpireTime(new Date(now.getTime() + 600000));
        lagouAuthCodeRepository.save(lagouAuthCode);
        return emailService.sendCode(email,code);
    }

    @GetMapping("/validate/{email}/{code}")
    public Integer validate(@PathVariable String email,@PathVariable String code) {
        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setEmail(email);
        lagouAuthCode.setCode(code);
        Example<LagouAuthCode> example = Example.of(lagouAuthCode);
        List<LagouAuthCode> lagouAuthCodes = lagouAuthCodeRepository.findAll(example);
        if (lagouAuthCodes == null || lagouAuthCodes.size() == 0) {
            return 1;//验证码错误
        } else {
            LagouAuthCode lagouAuthCode1 = lagouAuthCodes.get(0);
            Date now = new Date();
            if (lagouAuthCode1.getExpireTime().compareTo(now) < 0) {
                return 2;//超时
            } else {
                return 0;//正确
            }
        }

    }
}
